﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace CompleteReader.DocumentsPageDialogs
{
    public delegate void RecentItemOpenedDelegate(StorageFile file);


    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class RecentFilePage : Page
    {
        Data.RecentItemsData _recentItems;
        CommandBar _BottomCommandBar;
        private bool _AppBarIsAttached = true;

        public event RecentItemOpenedDelegate RecentItemOpened;

        Utilities.SharingHelper _SharingHelper;

        public RecentFilePage()
        {
            this.InitializeComponent();
            DisableSelectionOptions();
            this.Loaded += RecentFilePage_Loaded;
            this.Unloaded += RecentFilePage_Unloaded;
            this.IsEnabledChanged += RecentFilePage_IsEnabledChanged;
        }

        void RecentFilePage_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.NewValue);
        }


        public void ClearSelection()
        {
            RecentDocumentsGridView.SelectedItems.Clear();
        }

        
        async void RecentFilePage_Loaded(object sender, RoutedEventArgs e)
        {
            _recentItems = await CompleteReader.Data.RecentItemsData.GetItemSourceAsync(this);
            this.DataContext = _recentItems;
            _SharingHelper = Utilities.SharingHelper.GetSharingHelper();
            _SharingHelper.RetrieveSharingRecentItems += SharingHelper_RetrieveSharingRecentItems;
            _BottomCommandBar = this.BottomAppBar as CommandBar;
            CheckForEmptyList();
            if (!_AppBarIsAttached)
            {
                DetachAppbar();
            }
            //this.BottomAppBar = null;
        }

        void RecentFilePage_Unloaded(object sender, RoutedEventArgs e)
        {
            if (_SharingHelper != null)
            {
                _SharingHelper.RetrieveSharingRecentItems -= SharingHelper_RetrieveSharingRecentItems;
            }
        }

        IList<Data.RecentItem> SharingHelper_RetrieveSharingRecentItems()
        {
            if (RecentDocumentsGridView.SelectedItems.Count == 0)
            {
                Windows.ApplicationModel.Resources.ResourceLoader loader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                _SharingHelper.ErrorMessage = loader.GetString("DocumentsPage_SharingFailed_DocumentsNeeded");
                return null;
            }
            List<Data.RecentItem> selectedList = new List<Data.RecentItem>();
            foreach (Object selectedItem in RecentDocumentsGridView.SelectedItems)
            {
                Data.RecentItem recent = selectedItem as Data.RecentItem;
                if (recent != null)
                {
                    selectedList.Add(recent);
                }
            }
            return selectedList;
        }


        private void RecentDocumentsGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GridView viewer = sender as GridView;
            if (viewer.SelectedItems.Count == 0)
            {
                _BottomCommandBar.IsOpen = false;
                DisableSelectionOptions();
            }
            else
            {
                _BottomCommandBar.IsOpen = true;
                EnableSelectionOptions();
            }
        }

        private async void RecentDocumentsGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            Data.RecentItem recent = e.ClickedItem as Data.RecentItem;
            if (recent != null)
            {
                StorageFile file = null;
                try
                {
                    file = await _recentItems.GetRecentFileAsync(recent);
                }
                catch (Exception)
                {
                    // message
                }

                if (file != null)
                {
                    if (RecentItemOpened != null)
                    {
                        RecentItemOpened(file);
                    }
                }
                else
                {
                    Windows.ApplicationModel.Resources.ResourceLoader loader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                    Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(loader.GetString("DocumentsPage_RecentItems_FileNoLongerThere_Info"), loader.GetString("DocumentsPage_FileOpeningError_Title"));
                    await CompleteReader.Utilities.MessageDialogHelper.ShowMessageDialogAsync(md);
                    _recentItems.RemoveItems(new List<Data.RecentItem>() {recent});
                }
            }
        }

        #region App bar

        private void DeleteAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            IList<Data.RecentItem> recentItems = new List<Data.RecentItem>();
            foreach (Object selectedItem in RecentDocumentsGridView.SelectedItems)
            {
                recentItems.Add(selectedItem as Data.RecentItem);
            }
            _recentItems.RemoveItems(recentItems);
            CheckForEmptyList();
        }

        private void ClearSelectionAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            RecentDocumentsGridView.SelectedItems.Clear();
        }

        private async void DeleteAllAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            Windows.ApplicationModel.Resources.ResourceLoader loader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
            Windows.UI.Popups.MessageDialog messageDialog = new Windows.UI.Popups.MessageDialog(loader.GetString("DocumentsPage_RecentItems_ClearDialog_Info"), loader.GetString("DocumentsPage_RecentItems_ClearDialog_Title"));
            messageDialog.Commands.Add(new Windows.UI.Popups.UICommand(loader.GetString("DocumentsPage_RecentItems_ClearDialog_Clear_Option"), (command) =>
            {
                _recentItems.ClearList();
                CheckForEmptyList();
            }));
            messageDialog.Commands.Add(new Windows.UI.Popups.UICommand(loader.GetString("DocumentsPage_RecentItems_ClearDialog_Cancel_Option"), (command) =>
            {

            }));
            await CompleteReader.Utilities.MessageDialogHelper.ShowMessageDialogAsync(messageDialog);
        }

        private void CheckForEmptyList()
        {
            if (_recentItems.RecentItems.Count == 0)
            {
                DetachAppbar();
            }
        }

        public void DetachAppbar()
        {
            _AppBarIsAttached = false;
            if (_BottomCommandBar != null)
            {
                _BottomCommandBar.IsOpen = false;
            }
            this.BottomAppBar = null;
        }

        public void AttachAppbar()
        {
            _AppBarIsAttached = true;
            if (_recentItems.RecentItems.Count > 0)
            {
                this.BottomAppBar = _BottomCommandBar;
            }
        }

        private void EnableSelectionOptions()
        {
            DeleteAppBarButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
            ClearSelectionAppBarButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
            SelectionOptionsSeparator.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void DisableSelectionOptions()
        {
            DeleteAppBarButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            ClearSelectionAppBarButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            SelectionOptionsSeparator.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        #endregion App bar


    }
}
